import { resolve } from 'node:path'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import dts from 'vite-plugin-dts'
import { libInjectCss } from 'vite-plugin-lib-inject-css'
import replace from '@rollup/plugin-replace'

const monacoPrefix = 'monaco-editor/esm/vs'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), libInjectCss(), dts({ include: ['lib'] })],
  optimizeDeps: {
    include: [
      `${monacoPrefix}/language/json/json.worker`,
      `${monacoPrefix}/language/css/css.worker`,
      `${monacoPrefix}/language/html/html.worker`,
      `${monacoPrefix}/language/typescript/ts.worker`,
      `${monacoPrefix}/editor/editor.worker`,
    ],
  },
  // 关键：worker静态资源改为相对路径引入
  base: './',
  build: {
    target: 'esnext',
    minify: false,
    copyPublicDir: false,
    lib: {
      entry: resolve(__dirname, 'lib/main.ts'),
      formats: ['es'],
    },
    rollupOptions: {
      external: ['openinula', 'react', 'react-dom', 'react/jsx-dev-runtime', 'react/jsx-runtime'],
      output: {
        chunkFileNames: 'chunks/[name]-[hash].js',
        entryFileNames: '[name].js',
      },
    },
  },
  worker: {
    format: 'es',
    plugins: () => [
      replace({
        preventAssignment: true,
        values: {
          'process.env.NODE_ENV': JSON.stringify('production'),
        },
      }),
    ],
  },
})
